﻿/*******************************************************************************************
 * Copyright (c) 2006-2009 Alex Robson, Rob Simmons, Craig Israel, and Rachel Twyford
 *
 * Use of this software in any form requires that you have both 
 * read and agreed to the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions: 
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the 
 * documentation and/or other materials provided with the distribution.
 * Neither the name of Nvigorate nor the names of its contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using Nvigorate.Relational.Mapping.Interface;

namespace Nvigorate.Relational.Record
{
    /// <summary>
    /// The DataRecordCollection is an abstraction of the DataTable class
    /// which meets the IRecordCollection interface.
    /// </summary>
    public class DataRecordCollection : RecordCollectionBase, IDisposable
    {
        #region Protected Fields
        protected DataTable _table;
        protected override List<IRecord> records
        {
            get
            {
                List<IRecord> list = new List<IRecord>();
                foreach (DataRow row in _table.Rows)
                {
                    list.Add((DataRowRecord)row);
                }
                return list;
            }
        }
        #endregion

        #region IRecordCollection Members

        /// <summary>
        /// Allows the addition of a record object to the collection
        /// </summary>
        /// <param name="record">IRecord to add</param>
        public override void Add(IRecord record)
        {
            bool valid = true;
            if(Count != 0)
            {
                if(record.FieldCount != this[0].FieldCount)
                    valid = false;
                if(valid)
                {
                    foreach (string fieldName in record.FieldNames)
                    {
                        if(!this[0].FieldNames.Contains(fieldName))
                        {
                            valid = false;
                            break;
                        }
                    }
                }
            }

            if (valid)
            {
                if (record.GetType() == typeof (DataRowRecord))
                {
                    _table.Rows.Add(record.FieldValues);
                }
                else
                {
                    DataRow row = _table.NewRow();
                    foreach (DataColumn column in _table.Columns)
                    {
                        row[column.ColumnName] = record[column.ColumnName];
                    }
                }
            }
        }

        public override IRecord CreateRecord()
        {
            DataRow row = _table.NewRow();
            _table.Rows.Add(row);
            return new DataRowRecord(row);
        }

        /// <summary>
        /// Indicates if the end of collections has been reached
        /// </summary>
        public override bool EndOfRecords
        { 
            get { return _currentIndex == _table.Rows.Count - 1 || _table.Rows.Count == 0; }
        }

        /// <summary>
        /// Returns the record at the given index
        /// </summary>
        /// <param name="index">The index of the record to return</param>
        /// <returns>IRecord</returns>
        public override IRecord this[int index]
        {
            get
            {
                return new DataRowRecord(_table.Rows[index]);
            }
        }

        /// <summary>
        /// Returns the number of records in the collection
        /// </summary>
        public override int Count
        {
            get { return _table.Rows.Count; }
        }

        /// <summary>
        /// Returns all records as List &lt;IRecord&gt;
        /// </summary>
        /// <returns>List&lt;IRecord&gt;</returns>
        public override List<IRecord> GetRecordList()
        {
            return this.records;
        }

        public override string Name
        {
            get { return _table.TableName; }
        }

        public override void ReadSchema(ISourceMap sourceMap)
        {
            foreach (IAssignment assignment in sourceMap.Assignments)
            {
                _table.Columns.Add(new DataColumn(assignment.Source.Field));
            }
        }

        #endregion

        #region Public Methods
        public static implicit operator DataRecordCollection(DataTable table)
        {
            return new DataRecordCollection(table);
        }
        #endregion

        #region Constructors
        public DataRecordCollection()
        {
            _table = new DataTable();
        }

        public DataRecordCollection(string tableName)
        {
            _table = new DataTable(tableName);
        }

        public DataRecordCollection(DataTable table)
        {
            _table = table;
        }
        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            this._table.Dispose();
            this._table = null;
        }

        #endregion
    }
}